
//主题赛  操作类
const log = require("../../utils/log");
const CmdZt = require("../proto/CmdZt");
const gameZt = require("./gameZt");
const redisBase = require("../../common/RedisBase");

class GameZtOpt {
    static getInstance() {
        if (!GameZtOpt.instance) {
            GameZtOpt.instance = new GameZtOpt();
            return GameZtOpt.instance;
        } else {
            return GameZtOpt.instance;
        }
    }

    //
    /**
     * 当前题目两个人都答完 广播当前题目结果
     * @param curTid 正确答案
     * @param roomId 房间号
     * @returns {Promise<void>}
     */
    async broadCurTopicEnd(curTid,gameSession,roomId){
        log.info("=========两个人是答完，广播结果=========",);
        let ret = {
            type: CmdZt.GameAnswerEndBroadcast,
            data:{
                correctCid:curTid, //正确答案
                list:[] //用户信息
            }
        }

        //取gameInfo_list_zt 分数信息
        let gameInfo = await global.gameSerMgr.gameRedis.get_redis_in_room_list_zt_by_roomid(roomId);

        //取存在 session 里面的数据
        let infos = gameSession;
        log.info("=======broadCurTopicEnd=========",infos.length);
        let gameList = await redisBase.getGameListZt();
        for (let i = 0; i < infos.length; i++) {
            let d = infos[i].curData;
            let temp = {
                //答题用户的uid
                uid: d.uid,
                //状态 0是未答题 1是答对 2是答错
                status : d.status,
                //题目id
                tid : d.tid,
                //自己选择的答案id,默认从1开始,例如： 1 2 3 4 表示 答案 1 2 3 4
                cid : d.cid,
                //当前用户得分
                score: 0
            }

            for (let j = 0; j < gameList.length; j++) {
                let item = JSON.parse(gameList[j]);
                if(item.uid === d.uid && item.gamType === gameInfo.gameTypeZt){
                    log.warn('======item1212==========',temp.uid,temp.score)
                    temp.score = item.score;
                    break;
                }
            }
            ret.data.list.push(temp);
        }


        setTimeout(()=>{
            log.info("======broadCurTopicEnd111============")
            for (let i = 0; i < infos.length; i++) {
                let cfg = infos[i];
                let client = cfg.client;
                client.send(JSON.stringify(ret));
            }
            log.info("======broadCurTopicEnd222============")
        },500);
    }

    //广播下一题
    broadNextTopic(roomId,session){
        log.info("=======广播下一题=========")

        let ret = {
            type:  CmdZt.ThemeMatchGameNextBroadcast,
            data:{}
        }

        setTimeout(() => {
            log.info("======广播下一题1============")
            for (let i = 0; i < session.length; i++) {
                let cfg = session[i];
                let client = cfg.client;
                client.send(JSON.stringify(ret));
            }
            log.info("======广播下一题 end============")
        }, 1000)
    }

}
module.exports = GameZtOpt.getInstance();